<template>
  <div v-loading="loading" class="add-card">
    <header class="add-header">
      <el-page-header :content="isEdit ? '编辑月卡' : '新增月卡'" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">车辆信息</div>
        <div class="form">
          <!-- 表单校验：绑定数据 el-form ==> :model :rules  el-form-item ==> prop -->
          <el-form ref="carForm" :model="carForm" :rules="carRules" label-width="100px">
            <el-form-item label="车主姓名" prop="personName">
              <el-input v-model="carForm.personName" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input v-model="carForm.phoneNumber" />
            </el-form-item>
            <el-form-item label="车辆号码" prop="carNumber">
              <el-input v-model="carForm.carNumber" />
            </el-form-item>
            <el-form-item label="车辆品牌" prop="carBrand">
              <el-input v-model="carForm.carBrand" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container">
        <div class="title">最新一次月卡缴费信息</div>
        <div class="form">
          <el-form ref="feeForm" :model="feeForm" :rules="feeFormRules" label-width="100px">
            <el-form-item label="有效日期" prop="payTime">
              <el-date-picker
                v-model="feeForm.payTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item label="支付金额" prop="paymentAmount">
              <el-input v-model="feeForm.paymentAmount" />
            </el-form-item>
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="feeForm.paymentMethod">
                <el-option
                  v-for="item in payMethodList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>

    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="doSubmit">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { createRequiredRule, createPatternRule } from '@/utils/validate'
import { addCarCardAPI, getCarCardDetailAPI, updateCarCardAPI } from '@/api/car'

export default {
  data() {
    return {
      loading: false,
      // 车辆信息表单
      carForm: {
        personName: '',
        phoneNumber: '',
        carNumber: '',
        carBrand: ''
      },
      // 车辆信息的校验规则
      carRules: {
        personName: [createRequiredRule('请输入车主姓名')],
        phoneNumber: [createRequiredRule('请输入联系方式')],
        carNumber: [
          createRequiredRule('请输入车辆号码'),
          // 文档给的正则有错误，字母+数字的长度应该是7位
          createPatternRule(/^[陕京沪豫粤晋黑浙][\da-zA-Z]{7}$/, '请输入正确的车牌号')
        ],
        carBrand: [createRequiredRule('请输入车辆品牌')]
      },
      // 缴费信息表单
      feeForm: {
        payTime: '', // 支付时间
        paymentAmount: null, // 支付金额
        paymentMethod: '' // 支付方式
      },
      // 缴费规则
      feeFormRules: {
        payTime: [createRequiredRule('请选择支付时间')],
        paymentAmount: [createRequiredRule('请输入支付金额')],
        paymentMethod: [createRequiredRule('请选择支付方式', 'change')]
      },
      // 支付方式列表
      payMethodList: [
        {
          id: 'Alipay',
          name: '支付宝'
        },
        {
          id: 'WeChat',
          name: '微信'
        },
        {
          id: 'Cash',
          name: '线下'
        }
      ]
    }
  },
  async created() {
    // 在当前的项目中，因为表单数据只有一层，所以使用浅拷贝足矣
    // 如果是复杂的表单，有多层字段嵌套的话，这里一定要使用深拷贝
    this.__carForm = { ...this.carForm }
    this.__feeForm = { ...this.feeForm }

    // 拿路由参数，基于id调接口获取详情数据，完成数据回显
    const id = this.$route.query.id
    this.isEdit = !!id

    // 如果此时不是编辑状态，下面的代码不执行
    if (!this.isEdit) return
    // 缓存一下当前的月卡ID
    this.carInfoId = id
    this.loading = true
    const res = await getCarCardDetailAPI(id)
    // 缓存一下充值id
    this.rechargeId = res.data.rechargeId
    this.loading = false
    // res.data ==> carForm & feeForm
    this.carForm = {
      personName: res.data.personName,
      phoneNumber: res.data.phoneNumber,
      carNumber: res.data.carNumber,
      carBrand: res.data.carBrand
    }
    this.feeForm = {
      payTime: [
        res.data.cardStartDate,
        res.data.cardEndDate
      ], // 支付时间
      paymentAmount: res.data.paymentAmount, // 支付金额
      paymentMethod: res.data.paymentMethod
    }
  },
  methods: {
    doSubmit() {
      // 判断当前的操作状态：新增/编辑
      const data = {
        ...this.carForm,
        cardStartDate: this.feeForm.payTime[0],
        cardEndDate: this.feeForm.payTime[1],
        paymentAmount: this.feeForm.paymentAmount,
        paymentMethod: this.feeForm.paymentMethod
      }
      const fn = this.isEdit ? updateCarCardAPI : addCarCardAPI
      if (this.isEdit) {
        data.carInfoId = this.carInfoId
        data.rechargeId = this.rechargeId
      }
      // 1. 表单校验
      // 2. 调接口，发请求
      // 3. 提示用户，并调回列表页
      // 对表单进行手动（兜底）校验
      Promise.all([
        this.$refs.carForm.validate(),
        this.$refs.feeForm.validate()
      ])
        .then(() => {
          return fn(data)
        })
        .then(() => {
          this.$message.success('操作月卡成功')
          // 回到来的哪个入口页面
          this.$router.back()
          // 不需要做表单的重置，因为路由跳转会新建页面（重新初始化组件）
        })
        .catch(() => {
          console.log('校验失败')
        })
    },
    resetForm() {
      // 重置表单其实是做两件事：
      // 1. 重置数据
      // 2. 重置校验结果（清除错误提示）
      // 因为 resetFields 方法有时候不好用，所以没用，而是手动实现数据重置
      // clearValidate 是管用的，所以直接用
      this.carForm = { ...this.__carForm }
      this.$refs.carForm.clearValidate()

      this.feeForm = { ...this.__feeForm }
      this.$refs.feeForm.clearValidate()
    }
  }
}
</script>

<style scoped lang="scss">
.add-card {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }

    .preview {
      img {
        width: 100px;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
